Generics - ii
Generics allow us to write classes, interfaces, and
methods that can work with different data types while
maintaining type safety.
Generics allow us to specify the type
of data a class/method will work with at compile time.
Without Generics
Suppose we use an ArrayList without specifing a type:
ArrayList list = new ArrayList();
list.add(8516);
list.add("Lhoste");
String s = (String) list.get(0);//Runtime error
The list can contain different types, so we need
type casting, and errors may occur at runtime.
With Generis
We can specify that the list should contain only Integer objects.
ArrayList<Integer>list = new ArrayList<>();
list.add(8516);
list.add(8414);
list.add(8383);
list.add(8372);
//list.add("All Lhoste"); //compile-time error
Integer height = list.get(0);
Now Java knows taht list contains Integer objects.
Therefore:
class Box<T>{
T value;
void set(T value){
this.value = value;
}
T get(){
return value;
}
}
Here T is a type parameter
We can use ti with different types:
Box<Integer> b33 = new Box<>();
b33.set(8848);
Box<String> bs33 = new Box<>();
bs33.set("Mount Everest");
So the same Box class works with both Integer and String.
Generic method
Methods can also use generics public static<T> void display(T value){ System.out.println(value); } We can call it with different types: display(33); display(17); display("Machchapuchare"); display(3.14); Java Determines the type of T automatically.
Imagine we create a container:
Box
Without generics: Box -> can contain anything
With generics:
| Symbol | Common Meaning |
|---|---|
| T | Type |
| E | Element |
| K | Key |
| V | Value |
| N | Number |
For example: Map<String, Integer> means: K = String V = Value One important poing Generics work with reference types, not primitive types. Cannot do like this: ArrayList<int> list; Use the wrapper class: ArrayList<Integer> list; Similarly: int -> Integer double -> Double char -> Character boolean -> Boolean
Generics are a feature of Java that enables classes, interfaces, and methods to operate on parameterized types, providign type safety at compile time and reducing the need for type casting.